#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
   @Author: 即将拥有人鱼线的yjw
   @Time: 2024/3/7 15:46
   @File: risk_review_index_task.py
   @desc: 调度执行调度任务
"""
from AmlScripts.BasicFunction.common_test_prepare import common_test_prepare
from CommonScripts.index_rule_cal import indexJobAction
from BladeFerm.Lib.Common import logger
from qturboframe.lib.webdriver.exceptions import SeleniumError
from qturboframe.lib.utils.variable import Variable
from CommonScripts.blade import python_exec_sql

BladeVariable = Variable()


@common_test_prepare
def risk_index_task(input_data=None, ui_expect=None):
    '''
    子项调度任务执行、断言、修改页面参数
    '''
    env = BladeVariable.get_variable('varg_db_type')
    ruleNo = input_data.get('任务编号', None)
    logger.info(f'任务标号为: {ruleNo}')
    if ruleNo:  # 通过入参为任务编号来执行调度任务和用户得分断言
        bladeRuleNo = BladeVariable.get_variable("任务编号")
        if bladeRuleNo == ruleNo:
            logger.info(f'任务编号{ruleNo}已经执行，跳过直接断言！')
        else:
            BladeVariable.set_variable("任务编号", ruleNo)  # 更新任务编号
            indexJobAction(input_data={'jobName': ruleNo, 'env': env}, ui_expect={'flag': True})
        _check_risk_lever(ruleNo=ruleNo, ui_expect=ui_expect, env=env)
    else:
        raise SeleniumError(f"入参错误，没有 `任务编号`！")


def _check_risk_lever(ruleNo, ui_expect=None, env=None):
    '''
    用户风险子项得分对比
    '''
    # expect_date = ui_expect.get('期望')
    for key, value in ui_expect.items():
        inner_client_id = key.split('_')[0]
        sql = f"select distinct score_value from hsamlrc.amlrc_riskrules WHERE inner_client_id ='{inner_client_id}' and rules_no = '{ruleNo}'"
        logger.debug(f"查询 sql : {sql}")
        resultList = python_exec_sql(sql, env=env)
        logger.debug(f"查询 sql 结果: {resultList}")
        if value == '未命中' and not resultList:
            logger.info(f"客户 {inner_client_id} 得分为空，断言PASS!")
        elif value != '未命中' and not resultList:
            raise SeleniumError(f"客户 {inner_client_id} 得分为空，断言Fail!")
        else:
            check_flags = [0 for _ in resultList]
            for index, result in enumerate(resultList):
                score = int(result['score_value'])
                if score == int(value):
                    logger.info(f'用户{inner_client_id} 子项 {ruleNo}得分正确，得分为：{int(value)}')
                    check_flags[index] = 1
                else:
                    error = f'用户{inner_client_id} 子项{ruleNo}得分错误！实际得分：{int(value)}，预期得分：{score}'
                    logger.error(error)
                    raise SeleniumError(error)
            else:
                logger.info(f"检查结果成功!")